package com.fishingwithme.infrastructure.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.fishingwithme.infrastructure.FwmUserDetails;

import javax.crypto.SecretKey;
import java.util.Date;
@Slf4j
@Component
public class JwtUtils {

    private SecretKey secret;

    @Value("${jwt.secret}")
    public void setSecret(String secret) {
        this.secret =  Keys.hmacShaKeyFor(secret.getBytes());
    }

    @Value("${jwt.expirationMs}")
    private int expirationMs;

    public String generateJwtToken(FwmUserDetails userPrincipal) {
        return generateTokenFromUsername(userPrincipal.getUserId());
    }

    public String generateTokenFromUsername(Long username) {
        return Jwts.builder()
                .setSubject(username + "")
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + expirationMs))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public String getUserNameFromJwtToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
    }

    public boolean validateJwtToken(String authToken) {
        try {
            Jwts.parser().setSigningKey(secret).parseClaimsJws(authToken);
            return true;
        } catch (MalformedJwtException e) {
            log.error("Invalid JWT token: {}", e.getMessage());
        } catch (ExpiredJwtException e) {
            log.error("JWT token is expired: {}", e.getMessage());
            throw e;
        } catch (UnsupportedJwtException e) {
            log.error("JWT token is unsupported: {}", e.getMessage());
        } catch (IllegalArgumentException e) {
            log.error("JWT claims string is empty: {}", e.getMessage());
        }
        return false;
    }
}